package com.guagua.blog.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guagua.blog.entity.Article;
import com.guagua.blog.entity.Like;
import com.guagua.blog.mapper.LikeMapper;
import com.guagua.blog.service.ArticleService;
import com.guagua.blog.service.LikeService;
import com.guagua.common.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
@RequiredArgsConstructor
public class LikeServiceImpl extends ServiceImpl<LikeMapper, Like> implements LikeService {
    
    private final ArticleService articleService;
    
    @Override
    @Transactional
    public boolean toggleLike(Long articleId, Long userId) {
        // 检查文章是否存在并获取作者ID
        Article article = articleService.getById(articleId);
        if (article == null) {
            throw new BusinessException("文章不存在");
        }
        
        // 检查是否已点赞
        boolean exists = lambdaQuery()
            .eq(Like::getArticleId, articleId)
            .eq(Like::getUserId, userId)
            .exists();
            
        if (exists) {
            // 已点赞，取消点赞
            boolean removed = lambdaUpdate()
                .eq(Like::getArticleId, articleId)
                .eq(Like::getUserId, userId)
                .remove();
                
            if (removed) {
                // 更新文章点赞数
                articleService.lambdaUpdate()
                    .eq(Article::getId, articleId)
                    .setSql("like_count = like_count - 1")
                    .update();
                return false; // 返回false表示取消点赞
            }
        } else {
            // 未点赞，添加点赞
            Like like = new Like();
            like.setArticleId(articleId);
            like.setUserId(userId);
            like.setArticleAuthorId(article.getAuthorId()); // 设置文章作者ID
            like.setCreateTime(LocalDateTime.now());
            boolean saved = save(like);
            
            if (saved) {
                // 更新文章点赞数
                articleService.lambdaUpdate()
                    .eq(Article::getId, articleId)
                    .setSql("like_count = like_count + 1")
                    .update();
                return true; // 返回true表示点赞成功
            }
        }
        
        return exists; // 如果操作失败，返回原状态
    }

    @Override
    public boolean isLiked(Long articleId, Long userId) {
        return lambdaQuery()
            .eq(Like::getArticleId, articleId)
            .eq(Like::getUserId, userId)
            .exists();
    }
} 